<template>
  <div class="main">
    <div class="header_item">
      <van-nav-bar
        class="van_nav"
        title="购物车"
        fixed
        style="z-index: 15"
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
    <div class="van_item" v-for="item in datatable" :key="item.id">
      <van-checkbox v-model="item.paymentStatus" @click="Select"></van-checkbox>
      <van-icon name="cross" class="tubiao" @click="Delete(item)" />
      <van-card
        :style="item.id != 1 ? '' : 'border-top: 1px solid silver;'"
        :price="item.goodsPrice"
        :desc="item.desc"
        :title="item.goodsName"
        :thumb="item.goodsImg"
      >
      </van-card>
      <div class="van-footer_item">
        <van-stepper v-model="item.goodsNum" integer @change="addsub" />
      </div>
    </div>
    <div class="xiaoji" :style="{ display: datatable == 0 ? 'none' : 'block' }">
      <div class="footer_xiaoji">
        <p class="div_p">
          立减：<span>￥{{ this.lijian }}.00元</span> 小计：<span
            >￥{{ Coupon / 100 }}</span
          >
        </p>
      </div>
      <div class="footer_huiyuan">
        <p class="footer_p">
          <i class="dian">.</i>【会员特权】
          单笔实付满68元包邮（少数偏远地区除外）
        </p>
      </div>
      <van-coupon-cell
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        @click="showList = true"
      />
      <!-- 优惠券列表 -->
      <van-popup
        v-model="showList"
        round
        position="bottom"
        style="height: 90%; padding-top: 4px"
      >
        <van-coupon-list
          :coupons="coupons"
          :chosen-coupon="chosenCoupon"
          :disabled-coupons="disabledCoupons"
          @change="onChange"
          @exchange="onExchange"
        />
      </van-popup>
      <div class="footer-fuqian">
        <van-submit-bar
          :price="this.Coupon - this.lijian * 100"
          button-text="提交订单"
          @submit="onSubmit(Coupon - lijian * 100)"
        >
          <van-checkbox v-model="paymentStatus" @click="SelectAll">全选</van-checkbox>
        </van-submit-bar>
      </div>
    </div>
    <van-dialog v-model="show" title="请输入支付密码" show-cancel-button>
      <van-password-input
        :value="values"
        info="密码为 6 位数字"
        :error-info="errorInfo"
        :focused="showKeyboard"
        @focus="showKeyboard = true"
      />
      <van-number-keyboard
        v-model="values"
        :show="showKeyboard"
        @blur="showKeyboard = false"
      />
    </van-dialog>
  </div>
</template>
<script>
import { cartLists, delcart } from "../../api/index";

import Vue from "vue";
import { Dialog } from "vant";

// 全局注册
Vue.use(Dialog);
export default {
  name: "",
  data() {
    return {
      // 商品id
      Id:0,
      coupon: [],
      //优惠券
      chosenCoupon: -1, //当前选中优惠券的索引
      coupons: [], //可用优惠券列表
      disabledCoupons: [], //不可用优惠券列表
      showList: false, //开关按钮
      // 支付密码密码
      values: "",
      errorInfo: "",
      showKeyboard: true,
      paymentStatus: false,
      status:false,
      // 计算总价的参数
      lijian: 0, //打折
      value: "",
      prices: 0,
      priceInt: 0,
      dangjia: 0,
      show: false,
      datatable: [
        // {
        //   id: 1,
        //   src: "https://img01.yzcdn.cn/vant/apple-1.jpg",
        //   title: "一个尚明阿打算多",
        //   desc: "这是一个商品",
        //   price: 154.5,
        //   checked: false,
        //   value: 1,
        // }
      ],
      youhui: [
        {
          available: 1,
          condition: "无使用门槛\n满300减",
          reason: "",
          value: 5000,
          name: "优惠券名称",
          startAt: 1489104000,
          endAt: 1514592000,
          valueDesc: "50",
          unitDesc: "元",
        },
      ],
    };
  },
  // 计算属性 总价用计算属性
  computed: {
    // 计算总价格  every   reduce   come   filter    foreach   map
    Coupon() {
      return this.datatable.reduce((prev, cur) => {
        
        if (cur.paymentStatus) prev = prev + cur.goodsPrice * cur.goodsNum * 100;
        return prev;
      }, 0);
    },
  },
  created() {
    this.getGoods();
    this.Id = Number(this.$route.query.goodsId)
  },
  methods: {
    // 购物车列表
    async getGoods() {
      let obj = {
        goodsId: this.Id,
        pagenum: 1,
      };
            let {
            data: { result },
          } = await cartLists(obj);
          this.datatable = result;
    },
    // 删除商品
    Delete(item) {
      Dialog.confirm({
        title: "是否删除此商品",
      })
        .then(async () => {
            let obj = {
              userId:Number(window.localStorage.getItem("userId")),
              goodsId:item.goodsId
            }
          let {data,meta:{status,msg}} = await delcart(obj);
            if(status == 204){
              this.$notify({ type: 'success', message: msg });
              this.getGoods();
            }else{
              this.$notify({ type: 'warning', message: msg });
            }
        })
        .catch(() => {});
    },
    // 优惠券事件
    onChange(index) {
      this.showList = false;
      if (this.chosenCoupon == index) {
        this.lijian = 0;
        return (this.chosenCoupon = -1);
      } else {
        this.lijian = this.coupon[0].value / 100;
      }
      this.chosenCoupon = index;
    },
    onExchange(code) {
      this.coupons.push(this.coupon);
    },
    //跳转页面用
    onClickLeft() {
      this.$router.push({ path: `/Shops` });
    },
    // 选中确定单价
    Select() {
      const flag = this.datatable.every((item) => item.paymentStatus);
      const state = this.datatable.some((item)=> item.paymentStatus);
      // console.log(state);
        this.status = state ;
      this.paymentStatus = flag;
      if (this.chosenCoupon != -1) {
        this.lijian = 0;
        this.chosenCoupon = -1;
      }
    },

    //点击加号减号
    addsub(value) {
      this.prices = 0;
      this.priceInt = 0;
      this.prices = this.dangjia * 100 * value;
      this.priceInt = this.dangjia * value;
    },
    // 提交按钮
    onSubmit(price) {
      if(this.paymentStatus || this.status){
      let data = this.datatable;
      this.$router.push({ path: "/jiesuan", query: { price, data } });
      }else{
        Dialog.alert({
          title: '友情提示',
          message: '您还没有确定购物的商品!',
          theme: 'round-button',
          confirmButtonColor:'green'
        }).then(() => {
          // on close
        });
      }
     
    },
    // 全选按钮
    SelectAll() {
      this.datatable.map((item) => (item.paymentStatus = this.paymentStatus));
      if (this.chosenCoupon != -1) {
        this.lijian = 0;
        this.chosenCoupon = -1;
      }
    },
  },
  watch: {
    // 优惠券
    Coupon(newVal) {
      let Val = newVal / 100;
      this.coupon = [];
      if (Val > 300) {
        this.coupon.push(this.youhui[0]);
        this.coupons = this.coupon;
      } else {
        this.coupons = [];
        this.disabledCoupons = [];
      }
    },
  },
};
</script>
<style scoped lang='less'>
.main {
  .header_item {
    height: 48px;
  }
  .van_item {
    position: relative;

    .van-checkbox {
      position: absolute;
      z-index: 1;
      top: 35px;
      left: 2px;
    }
    .tubiao {
      position: absolute;
      z-index: 1;
      top: 10px;
      right: 15px;
    }
    .van-card {
      margin: 0;
      padding-left: 25px;
      padding-right: 0;
      padding-top: 0;
      border-bottom: 1px solid silver;
      .van-image {
        border: 1px solid rgb(214, 211, 211);
        margin-top: 3px;
      }
      .van-card__title {
        margin-top: 10px;
        margin-left: 5px;
      }
      .van-card__desc {
        margin-left: 5px;
        color: rgb(255, 102, 0);
        font-size: 8px;
      }
      .van-card__price {
        color: rgb(255, 102, 0);
        margin-left: 5px;
      }
    }
    .van-footer_item {
      width: 100px;
      height: 30px;
      position: absolute;
      z-index: 1;
      bottom: 8px;
      right: 5px;
    }
  }
  .xiaoji {
    height: 60px;
    background-color: rgb(243, 242, 242);
    padding: 10px 0;
    .footer_xiaoji {
      height: 30px;
      line-height: 30px;
      position: relative;
      width: 100%;
      background-color: white;
      .div_p {
        padding: 0;
        margin: 0;
        font-size: 12px;
        position: absolute;
        right: 5px;
        span {
          font-size: 12px;
          color: rgb(255, 102, 0);
        }
      }
    }
    .footer_huiyuan {
      height: 30px;
      line-height: 30px;
      background-color: rgb(247, 241, 231);
      .footer_p {
        padding: 0;
        margin: 0;
        font-size: 12px;
        margin-left: 15px;
        color: rgb(255, 102, 0);
        .dian {
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
  }
  .footer-fuqian {
    height: 200px;
  }
  .van-dialog {
    width: 338px;
    height: 557px;
    color: rgba(80, 80, 80, 1);
    background-color: rgba(255, 255, 255, 1);
    border-radius: 11px;
    font-size: 14px;
    line-height: 150%;
    text-align: center;

    .van-password-input {
      margin-top: 50px;
    }
  }
}
</style>